from flaskapp.exts import db


class User(db.Model):
    __tablename__ = 'users'

    userid = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    category = db.Column(db.String(60), nullable=False)
    is_admin = db.Column(db.Boolean, nullable=False, default=False)
    token = db.Column(db.String(512), unique=True, nullable=True)
    books_num = db.Column(db.Integer, nullable=True)

    def __init__(self, username, password, category, is_admin):
        self.username = username
        self.password = password
        self.category = category
        self.is_admin = is_admin
        self.token = None
        self.books_num = 0
        db.session.add(self)
        db.session.commit()

    def __repr__(self):
        return (f'<User {self.userid} {self.username} {self.password} {self.category} {self.is_admin} {self.token} '
                f'{self.books_num}>')

    def to_dict(self):
        return {
            'userid': self.userid,
            'username': self.username,
            'password': self.password,
            'category': self.category,
            'is_admin': self.is_admin,
            'token': self.token,
            'books_num': self.books_num
        }

    def addUser(self):
        db.session.add(self)
        db.session.commit()

    def deleteUser(self):
        db.session.delete(self)
        db.session.commit()

    def updateUser(self):
        db.session.commit()
